package zy.service.base.color.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.base.color.ColorDAO;
import zy.dao.sys.importinfo.ImportInfoDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.color.T_Base_Color;
import zy.entity.base.product.T_Base_Product_Color;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.service.base.color.ColorService;
import zy.util.CommonUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;
@Service
public class ColorServiceImpl implements ColorService{
	@Resource
	private ColorDAO colorDAO;

	@Resource
	private ImportInfoDAO importInfoDAO;
	
	@Override
	public PageData<T_Base_Color> page(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = colorDAO.count(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Color> list = colorDAO.list(param);
		PageData<T_Base_Color> pageData = new PageData<T_Base_Color>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	@Transactional
	@Override
	public void save(T_Base_Color color) {
		colorDAO.save(color);
	}
	@Transactional
	@Override
	public void save(Map<String,Object> param) {
		List<T_Base_Color> colorList = (List<T_Base_Color>)param.get("colorList");
		T_Import_Info t_Import_Info = (T_Import_Info)param.get("t_Import_Info");
		if(colorList != null && colorList.size()>0){
			colorDAO.save(colorList);
		}
		// 查询当前用户是否导入过数据
		T_Import_Info info = importInfoDAO.queryImportInfo(param);
		if(info != null){
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String last_error_filename = temp_uploaddir + File.separator + info.getIi_error_filename();
			File last_error_file = new File(last_error_filename);
			if (last_error_file.exists()) {
				last_error_file.delete();
			}
			ExcelImportUtil.deleteFile(last_error_file);
			importInfoDAO.updateImportInfo(t_Import_Info);
		}else {
			importInfoDAO.saveImportInfo(t_Import_Info);
		}
		
	}
	@Override
	public void update(T_Base_Color color) {
		colorDAO.update(color);
	}
	@Override
	public Integer queryByName(T_Base_Color color) {
		return colorDAO.queryByName(color);
	}
	
	@Override
	public T_Base_Color queryByID(Integer cr_id) {
		return colorDAO.queryByID(cr_id);
	}
	@Override
	public void del(Integer cr_id) {
		colorDAO.del(cr_id);
	}
	@Override
	public List<T_Base_Color> colorList(Map<String, Object> param) {
		return colorDAO.colorList(param);
	}
	
	/**
	 * 解析EXCEL 
	 */
	@Override
	public Map<String, Object> parseSavingCardInfoExcel(Workbook soureWorkBook,
			WritableWorkbook errsheet, int companyid) throws Exception {
		WritableSheet errorSheet = errsheet.getSheet(0);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<T_Base_Color> colorList = new ArrayList<T_Base_Color>();
		try {
			Sheet sheet = soureWorkBook.getSheet(0);
			int rsColumns = 2;//
			int rsRows = sheet.getRows(); // 行数
			System.out.println("共计: " + (ExcelImportUtil.getRightRows(sheet)-1) + "条");
			
			int j = 1;// 第二行开始写入错误信息, 错误条数
			int successRow = 0;// 导入成功条数
			String initial = "";
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("companyid", companyid);
			List<T_Base_Color> colors = colorDAO.colorList(param);
			
			for (int i = 1; i < rsRows; i++) { // 如第一行为属性项则从第二行开始取数据
				if (ExcelImportUtil.isBlankRow(sheet, i, rsColumns-1)) { // 空行则跳过
					continue;
				}
				// 储值卡编号
				Cell cell0 = sheet.getCell(0, i);
				String crName = cell0.getContents().trim();
				if (StringUtils.isBlank(crName)) {
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, j, rsColumns, "第 _" + (i+1) + "_条,颜色名称不能为空!");
					j++;
					continue;
				}
				boolean tag = false;
				for(int k=0;k<colors.size();k++){
					if(crName.equals(colors.get(k).getCr_name())){
						tag = true;
						break;
					}
				}
				if(tag){
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, j, rsColumns, "第 _" + (i+1) + "_条,颜色名已存在!");
					j++;
					continue;
				}
				
				// 数据表对象 crName
				T_Base_Color t_Base_Color = new T_Base_Color();
				t_Base_Color.setCr_name(crName);
				t_Base_Color.setCr_spell(StringUtil.Hanzi2SimpleSpelling(crName));
				t_Base_Color.setCompanyid(companyid);
				colorList.add(t_Base_Color);
				successRow++;
			}
			resultMap.put("colorList", colorList);
			resultMap.put("fail", j-1);// 错误条数
			resultMap.put("success", successRow);// 成功条数
		}catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	@Transactional
	@Override
	public void save_to_product(T_Base_Color color,String pd_code) {
		Assert.hasText(color.getCr_name(),"颜色名称不能为空！");
		T_Base_Color existColor = colorDAO.loadByName(color.getCr_name(), color.getCompanyid());
		T_Base_Product_Color model = new T_Base_Product_Color();
		if(existColor == null){//不存在该颜色，则新增颜色，保存商品颜色关联表
			colorDAO.save(color);
			model.setPdc_pd_code(pd_code);
			model.setPdc_cr_code(color.getCr_code());
			model.setCompanyid(color.getCompanyid());
		}else {//已存在该颜色，判断该商品是否已经关联该商品
			T_Base_Product_Color productColor = colorDAO.loadProductColor(pd_code, existColor.getCr_code(), color.getCompanyid());
			if(productColor != null){
				throw new RuntimeException("该商品已经关联颜色【"+color.getCr_name()+"】");
			}
			model.setPdc_pd_code(pd_code);
			model.setPdc_cr_code(existColor.getCr_code());
			model.setCompanyid(color.getCompanyid());
		}
		colorDAO.saveProductColor(model);
	}

}
